package com.asurplus.common.realname;

import com.alibaba.fastjson.JSONObject;
import com.asurplus.common.realname.api.ReportData;
import com.asurplus.common.realname.api.RequestBuilder;
import lombok.extern.slf4j.Slf4j;
import org.nutz.http.Request.METHOD;
import org.nutz.http.Response;
import org.nutz.http.Sender;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 防沉迷实名认证工具类
 */
@Slf4j
public class RealNameUtils {

    private RequestBuilder apiReg;
    private RequestBuilder apiRegCheck;
    private RequestBuilder apiReport;

    public RealNameUtils() {
        String appId = "963366599c6544679b95e426ce4a615b";
        String bizId = "1104020312";
        String secretKey = "c8e6535d69e8c4b733207c0d2f1c3f00";

        apiReg = new RequestBuilder("https://api.wlc.nppa.gov.cn/idcard/authentication/check", METHOD.POST, appId, bizId, secretKey);
        apiRegCheck = new RequestBuilder("http://api2.wlc.nppa.gov.cn/idcard/authentication/query", METHOD.GET, appId, bizId, secretKey);
        apiReport = new RequestBuilder("http://api2.wlc.nppa.gov.cn/behavior/collection/loginout", METHOD.POST, appId, bizId, secretKey);
    }

    /**
     * 请求实名认证
     *
     * @param userId 用户id
     * @param name   用户真实姓名
     * @param idNum  用户身份证号
     */
    public String checkRealName(String userId, String name, String idNum) {
        Map<String, Object> params = new HashMap<>();
        params.put("ai", getAi(userId));
        params.put("name", name);
        params.put("idNum", idNum);
        Sender sender = apiReg.build(params);
        Response response = sender.send();
        // 请求成功
        if (response.isOK()) {
            // 解析成为json
            JSONObject jsonObject = JSONObject.parseObject(response.getContent());
            // 返回了对应的错误码
            if (!"0".equals(jsonObject.getString("errcode"))) {
                log.error("实名认证错误，错误码：{}，错误描述：{}", jsonObject.getString("errcode"), jsonObject.getString("errmsg"));
                return null;
            }
            // 解析data
            jsonObject = JSONObject.parseObject(jsonObject.getString("data"));
            // 解析data.result
            jsonObject = JSONObject.parseObject(jsonObject.getString("result"));
            // 不是认证成功
            if (!"0".equals(jsonObject.getString("status"))) {
                if ("1".equals(jsonObject.getString("status"))) {
                    log.error("实名认证中");
                } else {
                    log.error("实名认证失败");
                }
                return null;
            }
            // 返回pi
            return jsonObject.getString("pi");
        } else {
            log.error("实名认证请求错误：{}", response.getStatus());
        }
        return null;
    }

    /**
     * 查询认证结果
     *
     * @param userId 用户id
     */
    public String queryRealName(String userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("ai", getAi(userId));
        Sender sender = apiRegCheck.build(params, "ai", getAi(userId));
        Response response = sender.send();
        if (response.isOK()) {
            // 解析成为json
            JSONObject jsonObject = JSONObject.parseObject(response.getContent());
            // 返回了对应的错误码
            if (!"0".equals(jsonObject.getString("errcode"))) {
                log.error("实名认证查询错误，错误码：{}，错误描述：{}", jsonObject.getString("errcode"), jsonObject.getString("errmsg"));
                return null;
            }
            // 解析data
            jsonObject = JSONObject.parseObject(jsonObject.getString("data"));
            // 解析data.result
            jsonObject = JSONObject.parseObject(jsonObject.getString("result"));
            if (!"0".equals(jsonObject.getString("status"))) {
                if ("1".equals(jsonObject.getString("status"))) {
                    log.error("实名认证中");
                } else {
                    log.error("实名认证失败");
                }
                return null;
            }
            return jsonObject.getString("pi");
        } else {
            log.error("实名查询请求错误：{}", response.getStatus());
        }
        return null;
    }

    /**
     * 上报数据
     *
     * @param grp
     */
    public void reportRealName(ArrayList<ReportData> grp) {
        Map<String, Object> params = new HashMap<>();
        params.put("collections", grp);
        Sender sender = apiReport.build(params);
        Response response = sender.send();
        if (response.isOK()) {
            String rs = response.getContent();
            System.out.println("result:" + rs);
        } else {
            System.out.println("server erro:" + response.getStatus());
        }
    }

    /**
     * 游戏内部对应的唯一标识
     */
    public static String getAi(String id) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0, len = id.length(); i < 31 - len; i++) {
            stringBuilder.append("1");
        }
        stringBuilder.append("F").append(id);
        return stringBuilder.toString();
    }
}
